/*
 *  Copyright (C) 2004 Cidero, Inc.
 *
 *  Permission is hereby granted to any person obtaining a copy of 
 *  this software to use, copy, modify, merge, publish, and distribute
 *  the software for any non-commercial purpose, subject to the
 *  following conditions:
 *  
 *  The above copyright notice and this permission notice shall be included
 *  in all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 
 *  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 *  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY IN CONNECTION WITH THE SOFTWARE.
 * 
 *  File: $RCSfile: SBReadThread.java,v $
 *
 */

package com.cidero.server.roku;

import java.io.*;
import java.net.*;
import java.util.logging.Logger;


/**
 * Thread to reading incoming messages from the Soundbridge control port
 * 4444.  Message are just discarded for now
 *
 */
public class SBReadThread implements Runnable
{
  private static Logger logger = Logger.getLogger("com.cidero.server.roku");

  Socket socket = null;
  long   promptCount = 0;

  /**
   * Constructor
   */
  public SBReadThread( Socket socket )
  {
    this.socket = socket;
  }
  
  public long getSketchPromptCount()
  {
    return promptCount;
  }
  

  private Thread readerThread = null;  // for clean shutdown via stop()
  
  /**
   * Thread run method
   */
  public void run()
  {
    logger.fine("SBReadThread: Running...");

    Thread thisThread = Thread.currentThread();
    
    BufferedReader reader;

    try 
    {
      reader = new BufferedReader( 
                    new InputStreamReader( socket.getInputStream() ) );
    }
    catch( Exception e )
    {
      logger.fine( "Error opening TCP socket for input" + e );
      return;
    }

    while( readerThread == thisThread )
    {
      //
      // Read lines one at a time, passing messages back to main thread
      // On error terminate read thread
      //
      try 
      {
        char c = (char)reader.read();
        
        if( c == '>' )
        {
          promptCount++;
          //System.out.println("sketch> ");
        }
        
        //System.out.println("SBReadThread: rx char - " + c );
      }
      catch( Exception e )
      {
        //logger.warning("SBReadThread: Error: " + e );
        return;
      }
    }
    
    logger.fine("SBReadThread: Shutting down...");
  }

  public void start()
  {
    readerThread = new Thread( this );
    readerThread.start();
  }
  
  public void stop()
  {
    readerThread = null;
  }
  
}
